﻿using System.Linq;
using System;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
using System.Web.Configuration;
using Castle.Windsor;
using Castle.Windsor.Configuration.Interpreters;

namespace LifeTree.Core
{
    public static class IoC
    {
        private static IWindsorContainer container = null;

        public static void Initialize()
        {
            Initialize(new WindsorContainer("Windsor.config"));
        }

        public static void Initialize(IWindsorContainer customContainer)
        {
            container = customContainer;
        }

        public static void RegisterInstance<T>(T instance)
        {
            EnsureInitialized();
            container.Kernel.AddComponentInstance<T>(instance);
        }

        public static void RegisterInstance<T>(string name, T instance)
        {
            EnsureInitialized();
            container.Kernel.AddComponentInstance(name, typeof(T), instance);
        }

        public static void RegisterType<I, T>() where T : class, I
        {
            EnsureInitialized();
            container.AddComponent<I, T>();
        }

        public static void RegisterType<I, T>(string key) where T : class, I
        {
            EnsureInitialized();
            container.AddComponent<I, T>(key);
        }

        public static T Resolve<T>(object parameters)
        {
            EnsureInitialized();
            return container.Resolve<T>(parameters);
        }

        public static T Resolve<T>()
        {
            EnsureInitialized();
            return container.Resolve<T>();
        }

        public static T Resolve<T>(IDictionary arguments)
        {
            EnsureInitialized();
            return container.Resolve<T>(arguments);
        }

        public static object Resolve(Type type)
        {
            return container.Resolve(type);
        }

        public static IEnumerable<T> ResolveAll<T>()
        {
            return container.ResolveAll<T>();
        }

        public static T Resolve<T>(string name)
        {
            if (!String.IsNullOrEmpty(name))
                return container.Resolve<T>(name);
            else
                return container.Resolve<T>();
        }

        private static void EnsureInitialized()
        {
            if (container == null)
                Initialize();
        }

        public static void Dispose()
        {
            if (container == null) return;
            container.Dispose();
            container = null;
        }

    }
}
